package com.yxh.fragment;

import java.io.Serializable;
import java.util.LinkedHashMap;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yxh.R;
import com.yxh.activity.AboutMeNotificationActivity;
import com.yxh.activity.ClassAddByInputActivity;
import com.yxh.activity.ClassAddByQrCodeActivity;
import com.yxh.activity.ClassTimeSettingActivity;
import com.yxh.activity.MainActivity;
import com.yxh.activity.WebViewActivity;
import com.yxh.adapter.HomeClassAdapter;
import com.yxh.dto.LessonDto;
import com.yxh.dto.LessonItemDto;
import com.yxh.service.Task;
import com.yxh.util.AppUtils;
import com.yxh.util.DateUtil;
import com.yxh.view.CommonDialog;
import com.yxh.view.DashedCircularProgress;
import com.yxh.view.DetectTouchGestureLayout;
import com.yxh.view.DetectTouchGestureLayout.onSwipeGestureListener;
import com.yxh.view.HomeRightPopup;
import com.yxh.view.pulltorefresh.PullToRefreshBase;
import com.yxh.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.yxh.view.pulltorefresh.PullToRefreshScrollView;
import com.yxh.view.swipemenulistview.SwipeMenu;
import com.yxh.view.swipemenulistview.SwipeMenuCreator;
import com.yxh.view.swipemenulistview.SwipeMenuItem;
import com.yxh.view.swipemenulistview.SwipeMenuListView;

public class HomeFragment extends BaseFragment implements OnClickListener {

	public final static int HOME_REQUEST_TIME = 0;

	private TextView mTitleBarText;
	private ImageView mTitleBarIcon;

	private View bottomView1, bottomView21, bottomView22;
	@SuppressWarnings("unused")
	private TextView bottomItem2Tv1, bottomItem2Tv2, bottomItem2Tv3;
	private ImageView bottomItem2Img1;
	private SwipeMenuListView listView;
	private HomeClassAdapter adapter;
	private SwipeMenuCreator creator;

	private DashedCircularProgress topProgress;
	private TextView topPercentTv, topDateTv, leftBackTv;

	private String lessonId;
	private volatile int current_pos = 0;
	private LessonDto lessonDto;
	private MainActivity act;

	private PullToRefreshScrollView mPullRefreshScrollView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		act = (MainActivity) getActivity();
	}

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_home, null);

		initView(view);

		initData(current_pos);

		initRegisterReceiver();

		return view;
	}

	public void initView(View view) {
		/** title **/
		view.findViewById(R.id.head_layout_back).setVisibility(View.GONE);
		mTitleBarText = (TextView) view.findViewById(R.id.head_layout_tv);
		mTitleBarText.setText(DateUtil.getDataString(current_pos));
		view.findViewById(R.id.head_layout_right).setVisibility(View.VISIBLE);
		view.findViewById(R.id.head_layout_right).setOnClickListener(this);
		mTitleBarIcon = (ImageView) view
				.findViewById(R.id.head_layout_right_img);
		mTitleBarIcon.setImageResource(R.drawable.home_title_add_icon);
		mTitleBarIcon.setVisibility(View.VISIBLE);

		view.findViewById(R.id.home_top_right_settime).setOnClickListener(this);

		/** init top view **/
		DetectTouchGestureLayout topView = (DetectTouchGestureLayout) view
				.findViewById(R.id.home_top_layout);
		topView.setSwipeGestureListener(new onSwipeGestureListener() {

			@Override
			public void onLeftSwipe() {
				goAfterDay();
			}

			@Override
			public void onRightSwipe() {
				goBeforeDay();
			}

		});

		topProgress = (DashedCircularProgress) view
				.findViewById(R.id.home_top_progress);
		topPercentTv = (TextView) view.findViewById(R.id.home_top_tv1);
		topDateTv = (TextView) view.findViewById(R.id.home_top_tv2);
		leftBackTv = (TextView) view.findViewById(R.id.home_top_left_back);
		leftBackTv.setOnClickListener(this);
		view.findViewById(R.id.beforeday).setOnClickListener(this);
		view.findViewById(R.id.afterday).setOnClickListener(this);

		/** init bottom view **/
		bottomView1 = (View) view
				.findViewById(R.id.home_bottom_layout_model1_item1);
		bottomView21 = (View) view
				.findViewById(R.id.home_bottom_layout_model2_item1);
		bottomView22 = (View) view
				.findViewById(R.id.home_bottom_layout_model2_item2);

		bottomView1.setOnClickListener(this);
		bottomItem2Tv1 = (TextView) view
				.findViewById(R.id.home_bottom_item2_tv1);

		bottomItem2Tv2 = (TextView) view
				.findViewById(R.id.home_bottom_item2_tv2);

		bottomItem2Tv3 = (TextView) view
				.findViewById(R.id.home_bottom_item2_tv3);

		bottomItem2Img1 = (ImageView) view
				.findViewById(R.id.home_bottom_item2_img);

		bottomItem2Img1.setOnClickListener(this);
		listView = (SwipeMenuListView) view
				.findViewById(R.id.home_bottom_item2_listview);
		mPullRefreshScrollView = (PullToRefreshScrollView) view
				.findViewById(R.id.pull_refresh_scrollview);
		mPullRefreshScrollView
				.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ScrollView> refreshView) {
						getLessonList(current_pos, 0);
					}
				});

	}

	private void initData(int pos) {
		getLessonList(pos, 1);
	}

	/** 获取首页默认课程列表 **/
	private void getLessonList(int pos, int isShowDialog) {
		// RETURN：arrLessoninfo（课程信息）*、arrData（课程内容列表type，title、intro)
		String timestamp = DateUtil.getTimeStamp(pos);
		// LogUtil.e("getLessonList timestamp-->" + timestamp);
		if (TextUtils.isEmpty(timestamp)) {
			return;
		}
		// captcha（验证码，必填）、mobile_No（手机号，必填）、device_code（设备码，必填）
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/get_list");
		map.put("timestamp", timestamp);
		if (!TextUtils.isEmpty(lessonId)) {
			map.put("lesson_id", lessonId);
		}
		map.put("pos", String.valueOf(pos));
		((MainActivity) getActivity()).getData(map, Task.GET_LESSON_LIST,
				isShowDialog);
	}

	/** 刷新Ui **/
	public void refreshHomeData(LessonDto dto) {
		// LogUtil.e("refreshHomeData -->" + dto);
		if(mPullRefreshScrollView!=null)
			mPullRefreshScrollView.onRefreshComplete();
		
		lessonDto = dto;
		current_pos = Integer.parseInt(dto.pos);

		mTitleBarText.setText(DateUtil.getDataString(current_pos));
		if (current_pos == 0) {
			leftBackTv.setVisibility(View.GONE);
		} else {
			leftBackTv.setVisibility(View.VISIBLE);
		}

		topProgress.setValue(lessonDto.percent);
		if (handler != null) {
			handler.removeMessages(refreshTopTv);
		}
		new AnminThread(Integer.parseInt(topPercentTv.getText().toString()),
				lessonDto.percent).start();

		String dateContent = getDateName(current_pos);
		topDateTv.setText(dateContent);

		if (lessonDto == null || TextUtils.isEmpty(lessonDto.lessonId)) {
			bottomView1.setVisibility(View.VISIBLE);
			bottomView21.setVisibility(View.GONE);
			bottomView22.setVisibility(View.GONE);

		} else {
			bottomView1.setVisibility(View.GONE);
			bottomView21.setVisibility(View.VISIBLE);
			bottomView22.setVisibility(View.VISIBLE);
			bottomItem2Tv1.setText(lessonDto.name);
			// bottomItem2Tv2.setText(dateContent);
			initListView(); // 装载listView
		}

	}

	/**
	 * 初始化listview
	 * 
	 */
	private void initListView() {
		if (lessonDto == null) {
			return;
		}

		if (lessonDto.list.size() == 0) {
			bottomItem2Tv3.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			return;
		}

		bottomItem2Tv3.setVisibility(View.GONE);
		listView.setVisibility(View.VISIBLE);

		adapter = new HomeClassAdapter(act, lessonDto.list);
		listView.setAdapter(adapter);
		if (creator == null) {
			creator = new SwipeMenuCreator() {
				@Override
				public void create(SwipeMenu menu) {

					// create "delete" item
					SwipeMenuItem deleteItem = new SwipeMenuItem(act);
					// set item background
					deleteItem
							.setBackground(R.drawable.main_home_bottom_list_right_bg);
					// set item width
					deleteItem.setWidth(AppUtils.dp2px(act, 60));
					// set a icon
					deleteItem.setIcon(R.drawable.main_bottom_item2_icon2);
					// add to menu
					menu.addMenuItem(deleteItem);
				}
			};
		}
		listView.setMenuCreator(creator);

		listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int pos, SwipeMenu menu, int index) {
				switch (index) {
				case 0:
					// LogUtil.e("pos -->" + pos);
					// LogUtil.e("menu -->" + menu);
					// LogUtil.e("index -->" + index);
					// menu.getMenuItem(index).setIcon(R.drawable.ic_launcher);
					// adapter.notifyDataSetChanged();
					// goCancleLesson(cList.get(pos).lessonId);
					break;
				default:
					break;
				}
				return true;
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {

				LessonItemDto dto = lessonDto.list.get(pos);
				if (!TextUtils.isEmpty(dto.url)) {
					Intent it = new Intent(act, WebViewActivity.class);
					it.putExtra("title", dto.title);
					it.putExtra("url", dto.url);
					startActivity(it);
				}

			}

		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.head_layout_right:
			showAddClassPop();
			break;

		case R.id.home_top_right_settime:
			goSetTime();
			break;

		case R.id.home_bottom_layout_model1_item1:
			showAddClassDialog();
			break;

		case R.id.home_top_left_back:
			goCurrentDay();
			break;

		case R.id.beforeday:
			goBeforeDay();
			break;

		case R.id.afterday:
			goAfterDay();
			break;

		case R.id.home_bottom_item2_img:
			goNotificationActivity();
			break;

		default:
			break;

		}
	}

	private void showAddClassPop() {
		HomeRightPopup pop = new HomeRightPopup(act);
		pop.showScanCodePanel(mTitleBarIcon);
	}

	private void goSetTime() {
		if (lessonDto == null || lessonDto.dateList.size() == 0) {

			showNoClassDialog();
			return;
		}

		Intent it = new Intent(getActivity(), ClassTimeSettingActivity.class);
		it.putExtra("resource", "0");
		it.putExtra("dto", (Serializable) lessonDto);
		startActivity(it);

	}

	private void showAddClassDialog() {
		CommonDialog dialog = new CommonDialog(act, CommonDialog.NORAML);
		dialog.setTitle("添加课程");
		dialog.setContent("通过 \"扫一扫\" 或者  \"课程码\"添加课程");
		dialog.setOkContent("课程码");
		dialog.setCancleContent("扫一扫");
		// dialog.setCancelable(false);
		dialog.setOkOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				Intent it = new Intent(act, ClassAddByInputActivity.class);
				it.putExtra("source", "1");
				startActivity(it);
			}
		});
		dialog.setCancleOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				Intent it = new Intent(act, ClassAddByQrCodeActivity.class);
				startActivity(it);
			}

		});
		dialog.show();
	}

	private void showNoClassDialog() {
		CommonDialog dialog = new CommonDialog(act, CommonDialog.NOTITLE);
		dialog.setTitle("您还没有课程,请先添加课程");
		dialog.setOkContent("课程码");
		dialog.setCancleContent("扫一扫");
		// dialog.setCancelable(false);
		dialog.setOkOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				Intent it = new Intent(act, ClassAddByInputActivity.class);
				it.putExtra("source", "1");
				startActivity(it);
			}
		});
		dialog.setCancleOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				Intent it = new Intent(act, ClassAddByQrCodeActivity.class);
				startActivity(it);
			}

		});
		dialog.show();
	}

	/**
	 * 回到当天
	 */
	private void goCurrentDay() {
		if (lessonDto == null || TextUtils.isEmpty(lessonDto.lessonId)) {
			showNoClassDialog();
			return;
		}

		initData(0);
	}

	/**
	 * 点击前一天
	 */
	private void goBeforeDay() {
		if (lessonDto == null || TextUtils.isEmpty(lessonDto.lessonId)) {
			showNoClassDialog();
			return;
		}
		initData(current_pos - 1);
	}

	/**
	 * 点击后一天
	 */
	private void goAfterDay() {
		if (lessonDto == null || TextUtils.isEmpty(lessonDto.lessonId)) {
			showNoClassDialog();
			return;
		}
		initData(current_pos + 1);
	}

	/**
	 * 跳到我得通知界面
	 */
	private void goNotificationActivity() {
		Intent it = new Intent(act, AboutMeNotificationActivity.class);
		startActivity(it);
	}

	/** 刷新 top 动画 **/
	private final static int refreshTime = 50;
	private final static int refreshTopTv = 0;
	private final static int refreshTopTvTime = 750;

	class AnminThread extends Thread {
		float cValue;
		float mValue;

		public AnminThread(int cValue, int mValue) {
			this.cValue = (float) cValue;
			this.mValue = (float) mValue;
		}

		public void run() {
			float addValue = (mValue - cValue)
					/ (refreshTopTvTime / refreshTime);
			// LogUtil.e("addValue -->" + addValue);
			// int a = mValue / ((20 * mValue) / refreshTime);
			if (addValue > 0) {
				while (cValue < mValue) {
					try {
						// 可加动画
						Thread.sleep(refreshTime);
						cValue += addValue;
						Message msg = handler.obtainMessage(refreshTopTv);
						msg.arg1 = ((int) cValue > 100) ? 100 : (int) cValue;
						handler.sendMessage(msg);
					} catch (Exception e) {

					}
				}
			} else if (addValue < 0) {
				while (cValue > mValue) {
					try {
						// 可加动画
						Thread.sleep(refreshTime);
						cValue += addValue;
						Message msg = handler.obtainMessage(refreshTopTv);
						msg.arg1 = ((int) cValue < 0) ? 0 : (int) cValue;
						handler.sendMessage(msg);
					} catch (Exception e) {

					}
				}
			} else {
				Message msg = handler.obtainMessage(refreshTopTv);
				msg.arg1 = (int) mValue;
				handler.sendMessage(msg);
			}
		}
	}

	Handler handler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == refreshTopTv) {
				topPercentTv.setText(String.valueOf(msg.arg1));

			}
		};
	};

	/**
	 * 广播 (刷新UI)
	 */
	public static final String REFRUSH_HOME = "refresh.homefragment.for.settingtime";
	public static final String REFRUSH_HOME_ADD_CLASS = "refresh.homefragment.for.addclass";
	public static final String REFRUSH_HOME_DEL_CLASS = "refresh.homefragment.for.delclass";
	private BroadcastReceiver homeReceiver;

	private void initRegisterReceiver() {
		homeReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent i) {
				String action = i.getAction();
				if (action.equals(REFRUSH_HOME)) {// 刷新Fragment
					getLessonList(current_pos, 1);
				} else if (action.equals(REFRUSH_HOME_ADD_CLASS)) {
					getLessonList(current_pos, 0);
				} else if (action.equals(REFRUSH_HOME_DEL_CLASS)) {
					getLessonList(0, 0);
				}
			}
		};

		IntentFilter i = new IntentFilter();
		i.addAction(REFRUSH_HOME);
		i.addAction(REFRUSH_HOME_ADD_CLASS);
		i.addAction(REFRUSH_HOME_DEL_CLASS);
		act.registerReceiver(homeReceiver, i);
	}

	private void unregisterReceiver() {
		act.unregisterReceiver(homeReceiver);
	}

	@Override
	public void onDestroy() {

		unregisterReceiver();
		super.onDestroy();
	}

	/**
	 * 换算时间名称
	 */
	private final long DAY = 24L * 60L * 60L;

	private String getDateName(int pos) {

		if (lessonDto == null || lessonDto.dateList.size() < 3) {
			return "未添加课程";
		}

		long t = Long.parseLong(DateUtil.date2TiemStamp(DateUtil
				.getDataString(pos))); // 当前时间

		long t1 = Long.parseLong(lessonDto.dateList.get(0).nodeDate); // 入院
		long t2 = Long.parseLong(lessonDto.dateList.get(1).nodeDate); // 手术
		long t3 = Long.parseLong(lessonDto.dateList.get(2).nodeDate); // 出院

		// LogUtil.e("t -->" + t);
		// LogUtil.e("t1 -->" + t1);
		// LogUtil.e("t2 -->" + t2);
		// LogUtil.e("t3 -->" + t3);
		// LogUtil.e("t1 - t -->" + (t1 - t));

		if (t <= t1) {
			return (t1 - t) / DAY == 0 ? "入院当天" : String.format("入院前%s天",
					AppUtils.foematInteger((t1 - t) / DAY));
		} else if (t > t1 && t <= t2) {
			return (t2 - t) / DAY == 0 ? "手术当天" : String.format("手术前%s天",
					AppUtils.foematInteger((t2 - t) / DAY));
		} else if (t > t2 && t <= t3) {
			return (t3 - t) / DAY == 0 ? "出院当天" : String.format("出院前%s天",
					AppUtils.foematInteger((t3 - t) / DAY));
		} else if (t > t3) {
			float c = ((float) (t - t3)) / DAY;
			return String.format("出院后%s天",
					AppUtils.foematInteger((long) Math.ceil(c)));
		} else {
			return "未知时间";
		}
	}

}